<?php

/**
 * buses actions.
 *
 * @package    SistemaRutasEc
 * @subpackage buses
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class boletounionActions extends sfActions {

    public function executeIndex($sfWebRequest) {

        $this->date = getdate();

        $this->dias_mes = date('t', mktime(0, 0, 0, $this->date['mon'], 1, $this->date['year']));
        $this->idco = Doctrine_Query::create()
                ->select('c.id_co')
                ->from('Cooperativa c')
                ->where('c.nombre = ?', "Union Cariamanga")
                ->andWhere('c.activo = ?', 1)
                ->execute(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);

        $this->rutasuni = Doctrine::getTable('ruta')->createQuery('r')
                ->where('r.id_co = ?', $this->idco)
                ->execute();
    }

    public function executeEdit(sfWebRequest $request) {
        if ($request->isMethod('POST')) {
            $fecha = date('Y-m-d', mktime(0, 0, 0, date('n'), date('d'), date('Y')));
            $idco = Doctrine_Query::create()
                    ->select('c.id_co')
                    ->from('Cooperativa c')
                    ->where('c.nombre = ?', "Union Cariamanga")
                    ->andWhere('c.activo = ?', 1)
                    ->execute(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);


            $boletos = Doctrine_Core::getTable('boleto')
                    ->createQuery('b')
                    ->where('b.dni = ?', $request->getParameter('ci'))
                    ->andWhere('b.origen = ?', "VEN")
                    ->andWhere('b.estado = ?', "VEN")
                    ->execute();

            $this->boletosuser = new ArrayObject();
            foreach ($boletos as $item):
                $turno = Doctrine_Query::create()->from('turno t')->where('t.id_tu = ?', $item->id_tu)->fetchOne();
                if ($turno->id_co == $idco) {
                    if ($turno->fecha > $fecha) {
                        $this->boletosuser[] = $item;
                    } else if ($turno->fecha == $fecha) {
                        if (date('H:i:s') - $turno->hora >= 2) {
                            $this->boletosuser[] = $item;
                        }
                    }
                }
            endforeach;

            $this->persona = Doctrine_Core::getTable('persona')
                    ->createQuery('r')
                    ->where('r.dni = ?', $request->getParameter('ci'))
                    ->fetchOne();
        }
    }

    public function executeShow(sfWebRequest $request) {
        $this->date = getdate();
        $this->dias_mes = date('t', mktime(0, 0, 0, $this->date['mon'], 1, $this->date['year']));
        $idbo = $request->getParameter('id_bo');

        $this->boleto = Doctrine_Query::create()->from('boleto b')->where('b.id_bo = ?', $idbo)->fetchOne();
        $turno = Doctrine_Query::create()->from('turno t')->where('t.id_tu = ?', $this->boleto->id_tu)->fetchOne();
        $this->ruta = Doctrine_Query::create()->from('ruta r')->where('r.id_ru = ?', $turno->id_ru)->fetchOne();
        $this->persona = Doctrine_Query::create()->from('persona p')->where('p.dni = ?', $this->boleto->dni)->fetchOne();
    }

    public function executeCanje(sfWebRequest $request) {
        if ($request->isXmlHttpRequest() && $request->isMethod('POST')) {

            $id_bo = $request->getParameter('idboleto');
            $id_fr = $request->getParameter('id_fr');
            $id_ru = $request->getParameter('id_ru');
            $hora = $request->getParameter('hora');
            $fecha = $request->getParameter('fecha');
            $asientos = $request->getParameter('asientos');
            $totalasientos = explode("-", $asientos);
            
            $json_data = array();
            $boleto = Doctrine_Query::create()->from('boleto b')->where('b.id_bo = ?', $id_bo)->fetchOne();            
            $turno = Doctrine_Query::create()->from('turno t')->where('t.id_ru = ?', $id_ru)->andwhere('t.id_fre = ?', $id_fr)->andwhere('t.fecha = ?', $fecha)->andwhere('t.hora = ?', $hora)->fetchOne();
            


            try {

                $asientosantiguos = Doctrine::getTable('asiento')
                        ->createQuery('a')
                        ->where('a.id_bo = ?', $boleto->id_bo)                        
                        ->execute();
                foreach ($asientosantiguos as $iteman):
                    $iteman->delete();
                endforeach;
                
                $boleto->setIdTu($turno->id_tu);                                
                $boleto->setOrigen(Boleto::ORIGEN_VENTA);
                $boleto->setEstado(Boleto::VENDIDO);                
                $boleto->save();

                for ($i = 0; $i < count($totalasientos); $i++) {
                    $newasiento = new Asiento();
                    $newasiento->setIdBo($boleto->id_bo);
                    $newasiento->setNumero($totalasientos[$i]);
                    $newasiento->save();
                }
                
                return $this->renderText(json_encode(array('status' => 'ok', 'id' => $boleto->id_bo)));
            } catch (sfException $error) {
                return $this->renderText(json_encode(array('status' => 'error', 'error' => 'Ha ocurrido un error al guardar el boleto. ' . $error->getMessage())));
            } catch (Exception $error) {
                $this->dispatcher->notify(new sfEvent($this, 'application.log', array('priority' => sfLogger::ERR, $error->getMessage())));
                return $this->renderText(json_encode(array('status' => 'error', 'error' => 'Ha ocurrido un error al guardar el boleto')));
            }
            
        }

        $this->forward404();
    }

    public function executeBuscarEscalas(sfWebRequest $request) {
        if ($request->isXmlHttpRequest()) {
            $id_co = $request->getParameter('cooperativa');
            $id_ru = $request->getParameter('ruta');
            $json_data = array();

            $regla = Doctrine_Query::create()->from('regla r')->where('r.id_co = ?', $id_co)->fetchOne();
            $ruta = Doctrine_Core::getTable('ruta')->find($id_ru);

            if ($regla->especial) {
                $escalas = Doctrine::getTable('escalaespecial')
                        ->createQuery('e')
                        ->where('e.id_ru = ?', $id_ru)
                        ->andWhere('e.ciudad <> ?', $ruta->salida)
                        ->execute();

                foreach ($escalas as $escala) {
                    $json_data[] = array(
                        'id' => $escala->id_ee,
                        'nombre' => $escala->ciudad . ' -- ' . $escala->costonormal . ' -- ' . $escala->costoespecial
                    );
                }
            } else {
                $escalas = Doctrine::getTable('escalanormal')
                        ->createQuery('e')
                        ->where('e.id_ru = ?', $id_ru)
                        ->andWhere('e.ciudad <> ?', $ruta->salida)
                        ->execute();

                foreach ($escalas as $escala) {
                    $json_data[] = array(
                        'id' => $escala->id_en,
                        'nombre' => $escala->ciudad . ' - ' . $escala->costonormal
                    );
                }
            }

            return $this->renderText(json_encode($json_data));
        }

        $this->forward404();
    }

    public function executeBuscarFrecuencias(sfWebRequest $request) {
        if ($request->isXmlHttpRequest()) {
            $id_ru = $request->getParameter('ruta');
            $dia = $request->getParameter('dia');
            $json_data = array();

            $query = Doctrine::getTable('frecuencia')
                    ->createQuery('f')
                    ->where('f.id_ru = ?', $id_ru)
                    ->andWhere('f.activo = true');

            if (date('d') == $dia) {
                $query->andWhere('f.hora > ?', date('H:i'));
            }

            $frecuencias = $query->execute();

            foreach ($frecuencias as $frn) {
                $json_data[] = array(
                    'id' => $frn->id_fr,
                    'nombre' => $frn->hora . " - " . ($frn->especial ? 'Especial' : 'Normal')
                );
            }

            return $this->renderText(json_encode($json_data));
        }

        $this->forward404();
    }

    public function executeBuscarBus(sfWebRequest $request) {
        if ($request->isXmlHttpRequest()) {
            $id_fr = $request->getParameter('frecuencia');
            $dia = $request->getParameter('dia');
            $json_data = array();

            $frecuencia = Doctrine_Query::create()->from('frecuencia f')->where('f.id_fr = ?', $id_fr)->fetchOne();
            $fecha_turno = date('Y-m-d', mktime(0, 0, 0, date('n'), $dia, date('Y')));

            $turnos = Doctrine::getTable('turno')
                    ->createQuery('t')
                    ->where('t.id_fre = ?', $id_fr)
                    ->andWhere('t.hora = ?', $frecuencia->hora)
                    ->andWhere('t.fecha = ?', $fecha_turno)
                    ->execute();
            foreach ($turnos as $tur):
                $busbus = Doctrine_Query::create()->from('bus b')->where('b.id_bu = ?', $tur->getIdBu())->fetchOne();
                $json_data[] = array(
                    'id' => $tur->id_tu,
                    'nombre' => $busbus->getDisco()
                );
            endforeach;

            return $this->renderText(json_encode($json_data));
        }
        $this->forward404();
    }

    public function executeBuscarAsientos(sfWebRequest $request) {

        if ($request->isXmlHttpRequest()) {

            $id_fr = $request->getParameter('frecuencia');
            $dia = $request->getParameter('dia');
            $hora = $request->getParameter('hora');

            $json_data = array();

            $fecha_turno = date('Y-m-d', mktime(0, 0, 0, date('n'), $dia, date('Y')));
            $turno = Doctrine_Query::create()->from('turno t')->where('t.id_fre = ?', $id_fr)->andwhere('t.fecha = ?', $fecha_turno)->andwhere('t.hora = ?', $hora)->fetchOne();

            $boletos = Doctrine::getTable('boleto')
                    ->createQuery('b')
                    ->where('b.id_tu = ?', $turno->id_tu)
                    ->andwhere('b.estado=?', Boleto::RESERVADO)
                    ->andwhere('b.estado=?', Boleto::VENDIDO)
                    ->execute();
            $totalasientos = new ArrayObject();

            foreach ($boletos as $bo):

                $asientos = Doctrine::getTable('asiento')
                        ->createQuery('a')
                        ->where('a.id_bo = ?', $bo->getIdBo())
                        ->execute();

                foreach ($asientos as $asbu) :
                    $totalasientos[] = $asbu;
                endforeach;

            endforeach;

            $numeroas = 02;
            for ($j = 1; $j <= 10; $j++) {
                $fa1 = $numeroas;
                $fa2 = $numeroas - 1;
                $fa3 = $numeroas + 1;
                $fa4 = $numeroas + 2;
                $ea1 = "Disponible";
                $ea2 = "Disponible";
                $ea3 = "Disponible";
                $ea4 = "Disponible";
                $filatotal = "";
                foreach ($totalasientos as $as):

                    if ($fa1 == $as->getNumero()) {
                        $ea1 = "No Disponible";
                    } elseif ($fa2 == $as->getNumero()) {
                        $ea2 = "No Disponible";
                    } elseif ($fa3 == $as->getNumero()) {
                        $ea3 = "No Disponible";
                    } elseif ($fa4 == $as->getNumero()) {
                        $ea4 = "No Disponible";
                    }

                endforeach;

                $filatotal = $fa1 . "-" . $ea1 . " || " . $fa2 . "-" . $ea2 . " |||| " . $fa3 . "-" . $ea3 . " || " . $fa4 . "-" . $ea4;
                $json_data[] = array(
                    'id' => $j,
                    'nombre' => $filatotal
                );
                $numeroas = $numeroas + 4;
            }
            return $this->renderText(json_encode($json_data));
        }
        $this->forward404();
    }

    public function executeBuscarDni(sfWebRequest $request) {

        if ($request->isXmlHttpRequest()) {
            $ci = $request->getParameter('ci');
            $json_data = array();
            $personas = Doctrine::getTable('persona')
                    ->createQuery('p')
                    ->where('p.dni = ?', $ci)
                    ->execute();

            foreach ($personas as $itemp):
                $json_data[] = array(
                    'id' => $itemp->dni,
                    'nombre' => $itemp->getFirstName(),
                    'apellido' => $itemp->getLastName(),
                    'telefono' => $itemp->getTelefono(),
                    'email' => $itemp->getEmailAddress()
                );
            endforeach;


            return $this->renderText(json_encode($json_data));
        }
        $this->forward404();
    }

    public function executeGuardarCliente(sfWebRequest $request) {

        $ci = $request->getParameter('ci');
        $nombre = $request->getParameter('nombre');
        $apellido = $request->getParameter('apellido');
        $telefono = $request->getParameter('telefono');
        $email = $request->getParameter('email');
        try {
            $newcliente = new Persona();
            $newcliente->setDni($ci);
            $newcliente->setFirstName($nombre);
            $newcliente->setLastName($apellido);
            $newcliente->setEmailAddress($email);
            $newcliente->setTelefono($telefono);
            $newcliente->save();
        } catch (sfException $error) {
            //$this->dispatcher->notify(new sfEvent($this, 'application.log', array('priority' => sfLogger::ERR, $error->getMessage())));
            return $this->renderText(json_encode(array('status' => 'error', 'message' => $error->getMessage())));
        } catch (Exception $error) {
            $this->dispatcher->notify(new sfEvent($this, 'application.log', array('priority' => sfLogger::ERR, $error->getMessage())));
            return $this->renderText(json_encode(array('status' => 'error', 'message' => 'Ha ocurrido un error al guardar ')));
        }
        return $this->renderText(json_encode(array('status' => 'ok')));
    }

    public function executeNew(sfWebRequest $request) {
        if ($request->isXmlHttpRequest() && $request->isMethod('POST')) {
            //$form = new BoletoForm();
            $ci = $request->getParameter('ci');
            $destino = $request->getParameter('destino');
            $valor = $request->getParameter('valor');
            $id_ru = $request->getParameter('id_ru');
            $id_fr = $request->getParameter('id_fr');
            $hora = $request->getParameter('hora');
            $fecha = $request->getParameter('fecha');
            $asientos = $request->getParameter('asientos');
            $totalasientos = explode("-", $asientos);

            $newboleto = new Boleto();
            $turno = Doctrine_Query::create()->from('turno t')->where('t.id_ru = ?', $id_ru)->andwhere('t.id_fre = ?', $id_fr)->andwhere('t.fecha = ?', $fecha)->andwhere('t.hora = ?', $hora)->fetchOne();


            //$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
            //if ($form->isValid())
            //{
            try {

                $newboleto->setIdTu($turno->id_tu);
                $newboleto->setDni($ci);
                $newboleto->setDestino($destino);
                $newboleto->setOrigen(Boleto::ORIGEN_VENTA);
                $newboleto->setEstado(Boleto::VENDIDO);
                $newboleto->setValor($valor);
                $newboleto->save();

                for ($i = 0; $i < count($totalasientos); $i++) {
                    $newasiento = new Asiento();
                    $newasiento->setIdBo($newboleto->id_bo);
                    $newasiento->setNumero($totalasientos[$i]);
                    $newasiento->save();
                }

                //$boleto = $form->save();
                return $this->renderText(json_encode(array('status' => 'ok', 'id' => $newboleto->id_bo)));
            } catch (sfException $error) {
                return $this->renderText(json_encode(array('status' => 'error', 'error' => 'Ha ocurrido un error al guardar el boleto. ' . $error->getMessage())));
            } catch (Exception $error) {
                $this->dispatcher->notify(new sfEvent($this, 'application.log', array('priority' => sfLogger::ERR, $error->getMessage())));
                return $this->renderText(json_encode(array('status' => 'error', 'error' => 'Ha ocurrido un error al guardar el boleto')));
            }
            //}
            //else
            //{
            //  return json_encode(array('status' => 'error', 'error' => 'El formulario no es válido'));
            //}         
        }

        $this->forward404();
    }

    public function executeDetalle(sfWebRequest $request) {
        $this->boleto = Doctrine_Core::getTable('Boleto')->find($request->getParameter('id'));
        $turno = Doctrine_Query::create()->from('turno t')->where('t.id_tu = ?', $this->boleto->id_tu)->fetchOne();
        $this->bus = Doctrine_Query::create()->from('bus t')->where('t.id_bu = ?', $turno->id_bu)->fetchOne();
        $asientos = Doctrine::getTable('asiento')
                ->createQuery('a')
                ->where('a.id_bo = ?', $this->boleto->getIdBo())
                ->execute();
        $this->valorboletototal = count($asientos) * $this->boleto->valor;
    }

    public function executeImprimir(sfWebRequest $request) {
        $this->boleto = Doctrine_Core::getTable('Boleto')->find($request->getParameter('id'));
        $turno = Doctrine_Query::create()->from('turno t')->where('t.id_tu = ?', $this->boleto->id_tu)->fetchOne();
        $this->bus = Doctrine_Query::create()->from('bus t')->where('t.id_bu = ?', $turno->id_bu)->fetchOne();
        $asientos = Doctrine::getTable('asiento')
                ->createQuery('a')
                ->where('a.id_bo = ?', $this->boleto->getIdBo())
                ->execute();
        $this->valorboletototal = count($asientos) * $this->boleto->valor;
        $this->setLayout('impresion');
    }

}